// pages/group/group.js
var g = require("../../utils/group")

Page({


// 在页面卸载时停止定时器
onUnload() {
    timer.clearTimer();
},

  matchDuration: function(e) {
    this.setData({
        matchDuration: e.detail.value
    });
},
  groupname:function(e){
       this.setData({
         groupname:e.detail.value
       });
  },
  groupnum:function(e){
    this.setData({
      groupnum:e.detail.value
    });
},
//莫惠淇改的功能
creategroup() {
  var database = wx.cloud.database();
  var groupname = this.data.groupname;
  var groupnum = this.data.groupnum;
  // 检查小组成员数量是否在 2 到 6 之间
  if (groupnum < 2) {
      wx.showToast({
          title: '人数不足，请重新组队',
          icon: 'none'
      });
  } else if (groupnum > 6) {
      wx.showToast({
          title: '人数过多，请重新组队',
          icon: 'none'
      });
  } else {
      database.collection("tb_group").add({
          data: {
              groupname: groupname,
              groupnum: groupnum
          }
      }).then((res) => {
          if (res) {
              wx.showToast({
                  title: '创建小组成功',
              });
          }
      }).catch((err) => {
          wx.showToast({
              title: '创建小组失败: ' + err.message,
              icon: 'none'
          });
      });
  }
},
kaishi(){
  var database = wx.cloud.database();
  var k = this.data.currentIndex;
  var matchid = this.data.result[k]._id;
  database.collection("tb_match").doc(matchid).update({
    data:{  
      beginTime:new Date()
    }
  }).then((res)=>{
    if(res)wx.showToast({
      title: '比赛开始成功',
    })
  })
    },
    jieshu(){
      var database = wx.cloud.database();
      var k = this.data.currentIndex;
      var matchid = this.data.result[k]._id;
      database.collection("tb_match").doc(matchid).update({
        data:{  
          endTime:new Date()
        }
      }).then((res)=>{
        if(res)wx.showToast({
          title: '比赛结束成功',
        })
      })
        },
  canjia(){
var userid = this.data.userid;
var username = this.data.username;
var k = this.data.index
var matchid = this.data.result[k]._id;
var matchname = this.data.result[k].title;
var database =  wx.cloud.database();
database.collection("tb_baoming").add({
  data:{
    userid:userid,
    username:username,
    matchid:matchid,
    matchname:matchname

  }
}).then((res)=>{
  if(res)wx.showToast({
    title: '报名成功',
  })
}).catch((err)=>{
  console.log(err)
});

  },
  shangchuan(){
   var that = this;

    wx.chooseMedia({
      count: 1,
      success(res) {
          console.log(res.tempFiles)
          var po = res.tempFiles[0].tempFilePath.lastIndexOf(".")
          var ext = res.tempFiles[0].tempFilePath.slice(po)
          wx.cloud.uploadFile({
              cloudPath: that.data.picname + ext,
              filePath: res.tempFiles[0].tempFilePath,
              success(res) {
                  console.log(res.fileID)
                  that.data.imageList.push(res.fileID)
                  that.setData({
                    imageList:that.data.imageList
                  });
              }
          })
      }
  })
},


  matchname:function(e){
this.setData({
  matchname:e.detail.value
})
  },
  changeCategory:function(e){
        this.setData({
          category:e.currentTarget.id//定向越野的第三个的点击事件，切换组队和建队的切换。
        });
  },
  shuru:function(e){
this.setData({
neirong:e.detail.value
});
  },
  //做了小组成员，比如创建队伍，有2个人，第三个人进去的话，就不可以进入
  rudui() {
    var k = this.data.index;
    var groupid = this.data.result[k]._id;
    var groupname = this.data.result[k].groupname;
    var userid = this.data.userid;
    var username = this.data.username;
    var database = wx.cloud.database();

    // 先获取队伍的人数限制
    database.collection("tb_group").where({
        _id: groupid
    }).field({
        groupnum: true
    }).get().then((groupRes) => {
        if (groupRes.data.length > 0) {
            var maxGroupNum = groupRes.data[0].groupnum;

            // 再查询当前队伍已有的人数
            database.collection("tb_rudui").where({
                groupid: groupid
            }).count().then((countRes) => {
                if (countRes.total < maxGroupNum) {
                    // 如果当前队伍人数小于限制人数，则允许入队，添加入队记录
                    database.collection("tb_rudui").add({
                        data: {
                            groupid: groupid,
                            groupname: groupname,
                            userid: userid,
                            username: username
                        }
                    }).then((res) => {
                        if (res) wx.showToast({
                            title: '加入小队成功',
                        })
                    }).catch((addErr) => {
                        console.log(addErr);
                    });
                } else {
                    // 如果队伍人数已满，给出相应提示
                    wx.showToast({
                        title: '队伍人数已满，无法加入',
                        icon: 'none'
                    });
                }
            }).catch((countErr) => {
                console.log(countErr);
            });
        } else {
            console.log('未找到对应队伍的人数限制信息');
            wx.showToast({
                title: '入队失败，队伍信息有误',
                icon: 'none'
            });
        }
    }).catch((groupErr) => {
        console.log(groupErr);
    });
},
  
  click(){
      var database = wx.cloud.database();
      var that = this;
      database.collection("tb_group").where({}).get().then((res)=>{
        var data = res.data;
        var result = [];
        
        for(let i=0;i<data.length;i++){
             if(data[i].groupname.match(that.data.neirong)){
               var d = data[i];
               result.push(d);
             }
        }
          that.setData({
               result:result
          });


      });
  },  
  dianji:function(e){
      this.setData({
        index:e.currentTarget.id,
        flag:true
      });
      var k = this.data.index
      var groupid = this.data.result[k]._id;
      var database = wx.cloud.database();
      var that = this;
      database.collection("tb_rudui").where({
          groupid:groupid
      }).get().then((res)=>{
           that.setData({
             zuyuan:res.data
           });
      });
  },
  sousuo(){
var neirong = this.data.neirong;
var database = wx.cloud.database();
database.collection("tb_match").where({}).get().then((res)=>{
var matches = res.data;
var result =[];

for(let i=0;i<matches.length;i++){
  var data = matches[i];
  if(data.title.match(neirong)){
    result.push(data);
  }    
  }
  this.setData({
    result:result   
    }); 
}).catch((err)=>{
console.log(err);
});

  }, 
  cansai:function(e){
    var that = this;
    var k = e.currentTarget.id;
    this.setData({
currentIndex:k 
    });
    var matchid = this.data.result[k]._id;
    var userid = this.data.userid;
    var database = wx.cloud.database();
    database.collection("tb_baoming").where({
      matchid:matchid
    }).get().then((res)=>{
      that.setData({
          xuanshou:res.data
      });
    }).catch((err)=>{console.log(err)});
    this.setData({
      index:e.currentTarget.id,
      biaozhi:true
    });
    //判断当前用户是否为对应比赛的创建者
    that.setData({
      isKaishi:false
    });
    var chuangjianzhe = that.data.result[k].userid;
    console.log("当前用户ID："+that.data.userid);
    console.log("当前创建者ID："+chuangjianzhe);
    if(that.data.userid == chuangjianzhe ){
      that.setData({
        isKaishi:true
      });
    }else{
      that.setData({
         isKaishi:false
      });
    }
    
    that.setData({
      isJieshu:false
    });
    var chuangjianzhe = that.data.result[k].userid;
    console.log("当前用户ID："+that.data.userid);
    console.log("当前创建者ID："+chuangjianzhe);
    if(that.data.userid == chuangjianzhe ){
      that.setData({
        isJieshu:true
      });
    }else{
      that.setData({
         isJieshu:false
      });
    }
  },

  
  picname:function(e){
this.setData({
picname:e.detail.value
});
  },


  delete(){
    console.log(this.data.currentIndex);
    this.data.imageList.splice(this.data.currentIndex,1);
    this.setData({
      imageList:this.data.imageList,
      flag3:false
     
    });

  },
  choose:function(e){
   
    var k = e.currentTarget.id;
    this.setData({
flag3:true,
currentImage:this.data.imageList[k],
currentIndex:k
    });
  },
    /**  
     * 页面的初始数据
     */
    data: {
      matchDuration: 0,
      zuyuan:[],
      groupname:null,//小组名
      groupnum:0,//小组人数
      isKaishi:true,
      xuanshou:[],
      currentIndex:0,
      flag3:false,
      currentImage:null,
      imageList:[],
      picname:null,
titles:g.list,
category:0,      
neirong:null,  
result:[],
index:0,
flag:false,
biaozhi:false,
matchname:null,
userid:null,
username:null
    },
  // 在 create 函数中保存比赛时长和开始时间

create() {
  var that = this;
  var database = wx.cloud.database();

  // 先查询是否已存在同名比赛
  database.collection("tb_match").where({
    title: that.data.matchname
  }).get().then((queryRes) => {
    if (queryRes.data.length > 0) {
      wx.showToast({
        title: '该比赛名称已存在，请更换名称',
        icon:'none'
      });
    } else {
      // 如果不存在同名比赛，则进行创建操作
      var data = {
        title: that.data.matchname,
        userid: that.data.userid
      };
      database.collection("tb_match").add({
        data: {
          title: that.data.matchname,
          userid: that.data.userid,
          imageList: that.data.imageList,
          matchDuration: that.data.matchDuration * 3600 // 将小时转换为秒后存入数据库
        }
      }).then((res) => {
        console.log("插入一条数据后数据库返回的数据：" + res);
        if (res) {
          wx.showToast({
            title: '成功插入数据',
          });
    
        } else {
          wx.showToast({
            title: '插入数据失败',
          })
        }
      }).catch((err) => {
        console.log(err);
      });
    }
  }).catch((err) => {
    console.log(err);
  });
},

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
      var that = this;
wx.getStorage({
  key:"userid",
  success(res){
that.setData({
  userid:res.data
});
//找到userid的对应的用户名
var database = wx.cloud.database();
database.collection("tb_user").where({
  _id:that.data.userid
}).get().then((msg)=>{
  that.setData({
    username:msg.data[0].name
  });
}).catch((err)=>{console.log(err)});
  }
})
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})